<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use App\Http\Repositories\SignatureHelper;

class OrderController extends Controller {
    //订单列表
    public function list(Request $request) {
        //获取参数
        $u_id = $request->u_id;
        $type = (empty($request->post('type'))) ? '7' : $request->post('type');
        $page = (empty($request->post('page'))) ? '1' : $request->post('page');

        $offset = ($page - 1) * 10;
        $limit = 10;

        $where = 'u_id = '.$u_id;
        switch ($type) {
            case '1':
                $where .= ' AND is_delivery = 0';
                break;
            case '2':
                $where .= ' AND is_delivery = 1 AND is_receiving = 0';
                break;
            case '3':
                $where .= ' AND is_delivery = 1 AND is_receiving = 1 AND is_trial = 1 AND is_recheck = 0';
                break;
            case '4':
                $where .= ' AND is_delivery = 1 AND is_receiving = 1 AND is_trial = 1 AND is_recheck = 1 AND is_remit = 0';
                break;
            case '5':
                $where .= ' AND is_delivery = 1 AND is_receiving = 1 AND is_trial = 1 AND is_recheck = 1 AND is_remit = 1 AND is_cancel = 0';
                break;
            case '6':
                $where .= ' AND is_delivery = 1 AND is_receiving = 1 AND is_trial = 1 AND is_recheck = 1 AND is_remit = 0 AND is_cancel = 1';
                break;
        }

        //查询数据
        $info = DB::table('orders')->whereRaw($where)->orderBy('create_at', 'DESC')->offset($offset)->limit($limit)->get();

        $list = array();
        foreach ($info as $k => $v) {
            $res['id'] = $v->id;
            $res['information'] = $v->information;
            $res['create_at'] = $v->create_at;
            if($v->is_delivery == 0) {
                $res['status'] = 1;
            }elseif ($v->is_delivery == 1 && $v->is_receiving == 0) {
                $res['status'] = 2;
            }elseif ($v->is_delivery == 1 && $v->is_receiving == 1 && $v->is_trial == 1 && $v->is_recheck == 0) {
                $res['status'] = 3;
            }elseif ($v->is_delivery == 1 && $v->is_receiving == 1 && $v->is_trial == 1 && $v->is_recheck == 1 && $v->is_remit == 0 && $v->is_cancel == 0) {
                $res['status'] = 4;
            }elseif ($v->is_delivery == 1 && $v->is_receiving == 1 && $v->is_trial == 1 && $v->is_recheck == 1 && $v->is_remit == 1 && $v->is_cancel == 0) {
                $res['status'] = 5;
            }elseif ($v->is_delivery == 1 && $v->is_receiving == 1 && $v->is_trial == 1 && $v->is_recheck == 1 && $v->is_remit == 0 && $v->is_cancel == 1) {
                $res['status'] = 6;
            }

            $imei = DB::table('order_phones')->where('o_id', $v->id)->pluck('imei')->toArray();
            $r_imei = (empty($imei)) ? '待完善' : implode(',', $imei);
            $res['imei'] = $r_imei;
            $res['picture'] = (empty($v->picture)) ? '' : explode(',', $v->picture)[0];
            $count = DB::table('order_phones')->where('o_id', $v->id)->where('is_confirm', 1)->count();
            $res['is_confirm'] = ($count > 0) ? 1 : 0;
            $list[] = $res;
        }

        //查询总数量
        $count = DB::table('orders')->whereRaw($where)->count();

        //返回数据
        $return['list'] = $list;
        $return['count'] = $count;
        $return['all_page'] = ceil($count / $limit);
        $return['page'] = $page;

        return ['code' => 1, 'message' => '请求成功', 'data' => $return];
    }

    //订单详情
    public function details(Request $request)
    {
        //获取参数
        $u_id = $request->u_id;
        $id = $request->post('id');

        //查询数据
        $order = DB::table('orders')->where('id', $id)->where('u_id', $u_id)->first();
        if(empty($order)) {
            return ['code' => 0, 'message' => '订单不存在', 'data' => ''];
        }
        $return['order_no'] = $order->order_no;
        $return['information'] = $order->information;
        $return['amount'] = $order->amount;
        $return['note'] = $order->note;
        $return['picture'] = explode(',', $order->picture);
        $return['orders'] = [];

        $phone = DB::table('order_phones')->where('o_id', $id)->get();

        foreach ($phone as $k => $v) {
            $res['op_id'] = $v->id;
            $res['title'] = (empty($v->title)) ? '' : $v->title;
            $res['level'] = (empty($v->level)) ? '等级待定' : $v->level;
            $res['note'] = (empty($v->note)) ? '' : $v->note;
            $res['imei'] = (empty($v->imei)) ? '' : $v->imei;
            $res['code'] = (empty($v->code)) ? '' : $v->code;
            $res['logistics_company'] = $v->logistics_company;
            $res['tracking_number'] = $v->tracking_number;
            if($v->is_confirm == 0) {
                $res['status'] = '待报价';     //待报价
            }elseif ($v->is_confirm == 1) {
                $res['status'] = '报价待确认';     //报价待确认
            }elseif ($v->is_confirm == 2 && $v->is_remit == 0) {
                $res['status'] = '待打款';     //待打款
            }elseif ($v->is_confirm == 2 && $v->is_remit == 1) {
                $res['status'] = '已打款';     //已打款
            }elseif ($v->is_confirm == 3 && $v->is_send_back == 0) {
                $res['status'] = '待寄回';     //待寄回
            }elseif ($v->is_confirm == 3 && $v->is_send_back == 1) {
                $res['status'] = '已寄回';     //已寄回
            }
            $res['price'] = (empty($v->price)) ? '价格待定' : ($res['status'] == '待报价') ? '价格待定' : $v->price;
            $return['orders'][] = $res;
        }

        //返回数据
        return ['code' => 1, 'message' => '请求成功', 'data' => $return];
    }

    //发货
    public function shipments(Request $request)
    {
        //获取参数
        $u_id = $request->u_id;
        $id = $request->post('id');
        $logistics_company = $request->post('logistics_company');
        $tracking_number = $request->post('tracking_number');

        if(empty($logistics_company) || empty($tracking_number)) {
            return ['code' => 0, 'message' => '缺少必要信息', 'data' => ''];
        }

        $user = DB::table('users')->where('id', $u_id)->first();
        if($user->identity != '1' && $user->identity != '2' && $user->identity != '3') {
            return ['code' => 0, 'message' => '用户没有成为供应商，暂时无法发货', 'data' => ''];
        }

        //查询数据
        $info = DB::table('orders')->where('id', $id)->where('u_id', $u_id)->first();
        if(empty($info)) {
            return ['code' => 0, 'message' => '订单不存在', 'data' => ''];
        }
        if($info->is_delivery != 0) {
            return ['code' => 0, 'message' => '订单已发货', 'data' => ''];
        }

        $update = ['is_delivery' => '1', 'logistics_company' => $logistics_company, 'tracking_number' => $tracking_number];
        $res = DB::table('orders')->where('id', $id)->where('u_id', $u_id)->update($update);

        if(!$res) {
            return ['code' => 0, 'message' => '发货失败', 'data' => ''];
        }
        if(Config::get('system.environment') == 'production') {
            $templateCode = 'SMS_166866150';
            //调取短信通道
            $templateParam = array(
                'name' => (empty($user->name)) ? $user->phone : $user->name,
                'order_no' => $info->order_no,
            );

            $aliYun = $this->aliYun($user->phone, $templateCode, $templateParam);
            if ($aliYun->Code != 'OK') {
                return ['code' => 0, 'message' => $aliYun->Message, 'data' => ''];
            }

            $content = DB::table('message_templates')->where('template_code', $templateCode)->value('content');
            $message = str_replace('{name}', (empty($user->name)) ? $user->phone : $user->name, $content);
            $message = str_replace('{order_no}', $info->order_no, $message);
            $inset = [
                'mobile' => $user->phone,
                'message_template_id' => $templateCode,
                'code' => '',
                'message' => $message,
                'send_at' =>date('Y-m-d H:i:s', time()),
                'overdue_at' =>date('Y-m-d H:i:s', time()+300),
                'is_use' => '1',
                'type' => '1'
            ];
            DB::table('messages')->insert($inset);
        }
        return ['code' => 1, 'message' => '发货成功', 'data' => $info->id];
    }

    //报价
    public function offer(Request $request)
    {
        //获取参数
        $op_id = $request->post('op_id');
        $type = $request->post('type');

        if($type != 1 && $type != 2) {
            return ['code' => 0, 'message' => '参数违规', 'data' => ''];
        }
        $info = DB::table('order_phones')->where('id', $op_id)->first();
        if(empty($info)) {
            return ['code' => 0, 'message' => '手机订单不存在', 'data' => ''];
        }
        if($info->is_confirm == 0) {
            return ['code' => 0, 'message' => '订单待报价', 'data' => ''];
        }
        if($info->is_confirm > 1) {
            return ['code' => 0, 'message' => '订单已确认或起取消', 'data' => ''];
        }

        $update = [];
        switch($type) {
            case '1':
                $update['is_confirm'] = 2;
                break;
            case '2':
                $update['is_confirm'] = 3;
                break;
        }
        $res = DB::table('order_phones')->where('id', $op_id)->update($update);

        $count = DB::table('order_phones')->where('o_id', $info->o_id)->where('is_confirm', '<', '2')->count();
        if($count == 0) {
            DB::table('orders')->where('id', $info->o_id)->update(['is_whole_confirmed' => '1']);

            //查询数据
            $info = DB::table('orders')->where('id', $info->o_id)->first();

            $user = DB::table('users')->where('id', $info->u_id)->first();

            if($type == '1') {
                if(Config::get('system.environment') == 'production') {
                    $templateCode = 'SMS_166866160';
                    //调取短信通道
                    $templateParam = array(
                        'name' => (empty($user->name)) ? $user->phone : $user->name,
                        'order_no' => $info->order_no,
                    );

                    $aliYun = $this->aliYun($user->phone, $templateCode, $templateParam);
                    if ($aliYun->Code != 'OK') {
                        return ['code' => 0, 'message' => $aliYun->Message, 'data' => ''];
                    }

                    $content = DB::table('message_templates')->where('template_code', $templateCode)->value('content');
                    $message = str_replace('{name}', (empty($user->name)) ? $user->phone : $user->name, $content);
                    $message = str_replace('{order_no}', $info->order_no, $message);
                    $inset = [
                        'mobile' => $user->phone,
                        'message_template_id' => $templateCode,
                        'code' => '',
                        'message' => $message,
                        'send_at' =>date('Y-m-d H:i:s', time()),
                        'overdue_at' =>date('Y-m-d H:i:s', time()+300),
                        'is_use' => '1',
                        'type' => '1'
                    ];
                    DB::table('messages')->insert($inset);
                }
            }
        }
        if(!$res) {
            return ['code' => 0, 'message' => '请求失败', 'data' => ''];
        }



        return ['code' => 1, 'message' => '请求成功', 'data' => ''];
    }

    /**
     * 发送短信
     *
     * @return bool|\stdClass
     */
    public function aliYun($mobile, $templateCode, $templateParam) {
        $params = array ();

        $aliYun = Config::get("sms.aliYun");

        // *** 需用户填写部分 ***
        // 是否启用https
        $security = false;

        // 获取用户AK信息
        $accessKeyId = $aliYun['accessKeyId'];
        $accessKeySecret = $aliYun['accessKeySecret'];

        // 短信发送手机号
        $params["PhoneNumbers"] = $mobile;

        // 短信签名
        $params["SignName"] = $aliYun['SignName'];

        // 模板短信code
        $params["TemplateCode"] = $templateCode;

        if(!empty($templateParam)) {
            // 模板变量
            $params['TemplateParam'] = $templateParam;
        }

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        //此处可能会抛出异常，注意catch
        $sign = new SignatureHelper();
        $content = $sign->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );

        return $content;
    }
}
